<?php
/*
 * send_gzip.php
 *
 * Copyright (C) 2006 - OS3 srl - http://www.os3.it
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
function _calc_etag ( $fname )
{
	$fh = @ fopen ( $fname, "r" );
	if ( ! $fh ) return array ( null, null );

	$s = fstat ( $fh );
	fclose ( $fh );

	$str = $s [ 'size' ] . "-" . $s [ 'ctime' ] . "-" . $s [ 'mtime' ];

	return array ( $str, $s [ 'mtime' ] );
}

function send_gzfile ( $fname, $verbose = false )
{
	$fname = str_replace ( "//", "/", $fname );

	if ( $verbose ) error_log ( "Send GZIP: $fname" );

	ob_start ( 'ob_gzhandler' );

	list ( $calc_etag, $mtime ) = _calc_etag ( $fname );
	if ( $calc_etag == null ) return;

	$mod_since  = array_key_exists ( 'HTTP_IF_MODIFIED_SINCE', $_SERVER ) ? $_SERVER [ 'HTTP_IF_MODIFIED_SINCE' ] : null;
	$none_match = array_key_exists ( 'HTTP_IF_NONE_MATCH', $_SERVER ) ? $_SERVER [ 'HTTP_IF_NONE_MATCH' ] : null;

	header ( "Etag: $calc_etag" );

	if ( $mod_since )
	{
		if ( ( $mtime - strtotime ( $mod_since ) ) <= 0 )
		{
			header ( "HTTP/1.x 304 Not Modified" );
			if ( $verbose ) error_log ( "Send GZIP: CACHE HIT (mtime) for: $fname" );
			return;
		}
	} else {
		if ( $none_match )
		{
			if ( $none_match == $calc_etag )
			{
				header ( "HTTP/1.x 304 Not Modified" );
				if ( $verbose ) error_log ( "Send GZIP: CACHE HIT (etag) for: $fname" );
				return;
			}
		}
	}

	$mtime_str = gmdate ( "D, d M Y H:i:s O", $mtime );
	header ( "Last-Modified: $mtime_str" );

	// print "MOD SINCE: [ " . ( $mtime - strtotime ( $mod_since ) ) . " - ETAG: [ $none_match / $calc_etag : " . ( $none_match == $calc_etag ) . "]\n";

	$f = fopen ( $fname, "r" );
	print fread ( $f, filesize ( $fname ) );
	fclose ( $f );
}

// print_r ( $_SERVER );
$dir = dirname ( dirname ( $_SERVER [ 'SCRIPT_FILENAME' ] ) );

send_gzfile ( "{$dir}/" . $_GET [ 'fname' ] );
?>
